import _ from 'lodash'
import { valid } from '@/utils'

const { isValidObject } = valid

const ANTD_TABLE_NAME = 'requestTable'

export const isAntdTable = (item) => item?.name === ANTD_TABLE_NAME

export const getInitState = (config) => {
  let result = {}
  if (Array.isArray(config?.items) && config?.items?.length) {
    config?.items.forEach((item) => {
      if (isAntdTable(item)) {
        result[item.callee || item.name] = {
          loading: false,
          pagination: {},
          list: []
        }
      }
    })
  }
  return result
}

export const formatTablePagination = (params = {}) => {
  const pageSize = _.isNumber(params?.limit) ? (params?.limit || 20) : 20
  const page = Math.floor(params?.offset / params?.limit)
  const current = _.isNumber(page) ? Math.max(page, 1) : 1
  const total = _.isNumber(params?.total) ? (params?.total || 0) : 0
  return {
    current,
    pageSize,
    total
  }
}

export const formatUpdateKeys = (params = {}, body = {}) => {
  if (!isValidObject(params) || !isValidObject(body)) {
    return {}
  }
  const keys = Object.keys(params)
  let result = {}
  keys.forEach((key) => {
    result[key] = _.get(body, params[key])
  })
  return result
}